<template>
    <div>
        <p>info:{{ info.name }}-{{ info.age }}</p>
        <p>age:{{ age }}</p>
        <p>name:{{ name }}</p>
        <button @click="changeInfo">changeInfo</button>
        <button @click="changeAge">changeAge</button>
        <button @click="changeName">changeName</button>
    </div>
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
    // watch是惰性的,第一次不会直接执行 
    // 更具体的说明当哪些状态发生变化时,触发侦听器的执行
    // 访问侦听状态
    setup() {
        const info = reactive({ name: "why", age: 18 })
        const name = ref("lion")
        const age = ref(18)



        // 侦听单个数据源 
        //1.侦听watch时,传入一个getter函数
        // watch(() => info.name, (newVal, oldVal) => {
        //     console.log(newVal, oldVal);
        // })
        // 2.传入一个可响应式的对象:reactive对象/ref对象
        //情况1:reactive对象获取到的newVal和oldVal本身都是reactive对象
        // watch(info, (newVal, oldVal) => {
        //     console.log(newVal, oldVal);
        // })
        // 如果希望是普通对象
        watch(() => { return { ...info } }, (newVal, oldVal) => {
            console.log(newVal, oldVal);
        })
        //情况2:ref对象获取newVal和oldVal是value值本身

        // watch(name, (newVal, oldVal) => {
        //     console.log(newVal, oldVal);
        // })
        // watch(age, (newVal, oldVal) => {
        //     console.log(newVal, oldVal);
        // })
        // // 侦听多个数据源
        // watch([name, age], (newVal, oldVal) => {
        //     console.log(newVal, oldVal);    //对应新数组数据和旧数组数据
        // })

        const changeInfo = () => {
            info.name = "coderwhy"
            info.age = 19
        }
        const changeName = () => {
            name.value = "coder111"
        }
        const changeAge = () => {
            age.value = 19
        }
        return {
            info,
            name,
            age,
            changeInfo,
            changeName,
            changeAge,
        }
    }
}
</script>

<style lang="scss" scoped>
</style>